package bma.common.netty.handler;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bma.common.langutil.log.LogPrinter;
import bma.common.langutil.log.LogPrinter.LEVEL;

public class ChannelHandlerShowConnect implements ChannelUpstreamHandler {

	private LogPrinter log;

	public ChannelHandlerShowConnect(LogPrinter log) {
		super();
		this.log = log;
	}

	public ChannelHandlerShowConnect(String logName, String logType) {
		this(new LogPrinter(LoggerFactory.getLogger(logName),
				LEVEL.valueOf(logType)));
	}

	public ChannelHandlerShowConnect(Logger log, LEVEL logLevel) {
		this(new LogPrinter(log, logLevel));
	}

	public LogPrinter getLog() {
		return log;
	}

	public void setLog(LogPrinter log) {
		this.log = log;
	}

	@Override
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (e instanceof ChannelStateEvent) {
			ChannelStateEvent evt = (ChannelStateEvent) e;
			switch (evt.getState()) {
			case CONNECTED:
				if (evt.getValue() != null) {
					if (log.isEnabled()) {
						log.print("{} connected", ctx.getChannel()
								.getRemoteAddress());
					}
				} else {
					if (log.isEnabled()) {
						log.print("{} disconnect", ctx.getChannel()
								.getRemoteAddress());
					}
				}
				break;
			}
		}
		ctx.sendUpstream(e);
	}

	@Override
	public String toString() {
		return "ShowConnect()";
	}
}
